import Router from '@koa/router';
import { camelCaseToKebab } from 'camelcase-to-kebab'
import logger from '../lib/log4js.js';
export class BaseRouter {

    constructor(mapper) {
        this.mapper = mapper;
        const entityName = mapper.getName();
        const prefix = "/" + camelCaseToKebab(entityName).substring(1);
        this.prefix = prefix;
        this.router = new Router({ prefix });

    }
    getRouter() {
        this.router.get("/find-by-pk", async (ctx) => {
            const { pk } = ctx.request.query;
            this.ctxBody(ctx, { data: await this.mapper.findOne({ pk }) })
        })
        this.router.get("/find-pager", async (ctx) => {
            const { page, offset, where, order } = ctx.request.query;
            this.ctxBody(ctx, { data: await this.mapper.findPager({ page, offset, where, order }) });
        })
        this.router.get("/find-list", async (ctx) => {
            const { where, order } = ctx.request.query;
            this.ctxBody(ctx, { data: await this.mapper.findList({ where, order }) });
        })

        this.router.post("/save", async (ctx) => {
            const values = ctx.request.body;
            this.ctxBody(ctx, { data: await this.mapper.save({ values }) });
        })
        this.router.post("/save-batch", async (ctx) => {
            const records = ctx.request.body;
            this.ctxBody(ctx, { data: await this.mapper.saveBatch({ records }) });
        })
        this.router.post("/update", async (ctx) => {
            const { values, where } = ctx.request.body;
            this.ctxBody(ctx, { data: await this.mapper.update({ values, where }) })
        })
        this.router.post("/save-or-update", async (ctx) => {
            const { values } = ctx.request.body;
            this.ctxBody(ctx, { data: await this.mapper.saveOrUpdate({ values }) });
        })

        this.router.post("/remove", async (ctx) => {
            const { where } = ctx.request.body;
            this.ctxBody(ctx, { data: await this.mapper.remove({ where }) })
        })
        this.makeRouter(this.router);
        return this.router;
    }
    makeRouter(router) { }
    ctxBody(ctx, { data, code = 200, success = true }) {
        ctx.body = {
            code,
            success,
            data
        };
    }


}